package com.snap.awesomeserial.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;

import com.snap.awesomeserial.BuildConfig;
import com.snap.awesomeserial.ui.SettingActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Eason on 2018/7/24 .
 */
public class ApkUtils {
    public static boolean isSystemApp(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            Log.e("Rachel", "结果：" + (info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM));
            return (info != null) && (info.applicationInfo != null) &&
                    ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 检查apk的更新
     *
     * @param context 上下文
     */
    public static void checkUpdate(Context context) {
        List<String> pathList = getUSBPaths(context);
        if (pathList == null || pathList.size() == 0) {
            if (context instanceof SettingActivity) {
                ToastUtils.get().showText("未检测到U盘插入");
            }
            return;
        }
        List<File> apkList = new ArrayList();
        for (String path : pathList) {
            traverseFolder(path, apkList);
        }
        File latestApk = null;
        int myCode = BuildConfig.VERSION_CODE;
        for (int i = 0; i < apkList.size(); i++) {
            int code = getApkVersionCode(context, apkList.get(i));
            if (code > myCode) {
                latestApk = apkList.get(i);
                myCode = code;
            }
        }
        if (latestApk != null) {
            checkVersion(context, latestApk.getAbsolutePath());
        } else {
            ToastUtils.get().showText("未发现新版本安装包！");
        }
    }

    /**
     * 遍历路径下文件
     */
    private static void traverseFolder(String path, List<File> apkList) {
        File file = new File(path);
        if (!file.exists()) return;
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            for (File child : files) {
                if (child.isDirectory()) {
                    traverseFolder(child.getAbsolutePath(), apkList);
                } else {
                    if (child.getName().startsWith("Mole" + BuildConfig.FLAVOR)
                            && child.getName().endsWith(".apk")) {
                        apkList.add(child);
                    }
                }
            }
        }
    }

    private static int getApkVersionCode(Context context, File file) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(file.getAbsolutePath(), PackageManager.GET_ACTIVITIES);
        if (info != null) {
            return info.versionCode;
        }
        return 0;
    }

    /**
     * 检查版本是否大于当前安装包
     *
     * @param context 上下文
     * @param apkPath U盘内apk安装包的路径
     */
    private static void checkVersion(Context context, String apkPath) {
        boolean isGetActivity = check(context, apkPath);
        if (isGetActivity) {
            PackageInfo packageInfoLocal = null;
            PackageInfo packageInfo = null;
            PackageManager pm = context.getPackageManager();
            try {
                packageInfoLocal = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                packageInfo = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            if (packageInfoLocal != null) {
                int versionCode = packageInfoLocal.versionCode;
                String packageName = context.getPackageName();
                if (TextUtils.equals(packageName, packageInfo.packageName)) {
                    if (versionCode < packageInfo.versionCode) {
                        ToastUtils.get().showText("APK更新：开始安装");
                        RootShellCmd.getInstance().silentInstall(apkPath);
                    } else if (versionCode > packageInfo.versionCode) {
                        ToastUtils.get().showText("APK更新：无法安装，版本过低");
                    } else {
                        ToastUtils.get().showText("APK更新：已是最新版本");
                    }
                } else {
                    ToastUtils.get().showText("APK更新：无法安装，包名不一致");
                }
            }
        } else {
            ToastUtils.get().showText("APK更新：无法安装，不是一个可以使用的安装包");
        }
    }

    public static List<String> getUSBPaths(Context con) {
        String[] paths;
        List<String> data = new ArrayList<>();
        // include sd and usb devices
        StorageManager storageManager = (StorageManager) con
                .getSystemService(Context.STORAGE_SERVICE);
        try {
            paths = (String[]) StorageManager.class.getMethod("getVolumePaths", new Class[0]).invoke(
                    storageManager, new Object[]{});
            for (String path : paths) {
                String state = (String) StorageManager.class.getMethod("getVolumeState",
                        String.class).invoke(storageManager, path);
                if (state.equals(Environment.MEDIA_MOUNTED) && !path.contains("emulated")) {
                    data.add(path);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 拥有系统签名的app无法通过这种方式更新
     *
     * @param context 上下文
     * @param file    安装文件
     */
    @Deprecated
    private static void install(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) {
            //把文件封装成Uri对象后再提供给外部，提高应用的安全性
            Uri uri = FileProvider.getUriForFile(context, "com.snap.awesomeserial.fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    /**
     * 必须拥有读取权限
     * 作为U盘里的安装包还应申请U盘读取权限
     *
     * @param context  上下文
     * @param filePath U盘内apk安装包的路径
     * @return 是否为可以使用的安装包
     */
    private static boolean check(Context context, String filePath) {
        PackageManager pm = context.getPackageManager();
        return pm.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES) != null;
    }
}
